package com.sea.base.activities

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.Application
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.annotation.RequiresApi
import androidx.viewbinding.ViewBinding
import com.sea.base.activities.databinding.BaseActivityTransBinding
import com.sea.base.ext.global.doOnNextActivityCreated
import com.sea.base.ext.global.intentNew
import com.sea.base.ext.global.singleApplication
import com.sea.base.ext.global.throwIfDebug
import com.sea.base.utils.param.BundleParams
import java.util.concurrent.atomic.AtomicInteger

/**
 * 一个纯透明的activity
 */
internal class TransparentActivity : BaseFullscreenKtActivity<BaseActivityTransBinding>() {
    companion object {
        private val callbackIdIncrement = AtomicInteger()
        private var callbackMap = hashMapOf<Int, (TransparentActivity) -> Unit>()

        /**
         * 目前为回调方式，所以不支持被杀死后重建
         *
         * 使用场景：
         * 全局弹窗（不会因activity突然关闭而被关闭）
         * 拉起app（通知栏回到app）
         */
        fun doOnVisible(callback: (TransparentActivity) -> Unit) {
            val id = callbackIdIncrement.incrementAndGet()
            callbackMap[id] = callback
            singleApplication.startActivity(
                intentNew<TransparentActivity>()
                    .putExtra("callbackId", id)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            )
        }
    }

    private var activityLifecycleCallbacks: Application.ActivityLifecycleCallbacks? = null

    @BundleParams("callbackId")
    private val callbackId: Int = 0

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        reInitNewIntentParams()
        getAndInvoke()
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun init(savedInstanceState: Bundle?) {
        val callback = callbackMap[callbackId]
        if (callback == null) {
            //可能是因为重建导致回调为null，这里直接关闭
            finish()
            return
        }

        val flRoot = View(this)
        //任何触碰都将会关闭页面，防止业务出现bug导致用户无法操作
        flRoot.setOnTouchListener { _, _ ->
            finish()
            true
        }
        super.setContentView(flRoot)

        getAndInvoke()

        keepTop()
    }

    private fun getAndInvoke() {
        val callback = callbackMap.remove(callbackId)
        throwIfDebug("未知错误，callback为null") { callback == null }
        callback?.invoke(this)
    }

    /**
     * 防止在弹窗过程中被其他界面压下去
     */
    @SuppressLint("MissingPermission")
    private fun keepTop() {
        activityLifecycleCallbacks = application.doOnNextActivityCreated {
            activityLifecycleCallbacks = null
            if (it is TransparentActivity) {
                keepTop()
            } else {
                (getSystemService(ACTIVITY_SERVICE) as ActivityManager).moveTaskToFront(taskId, ActivityManager.MOVE_TASK_NO_USER_ACTION)
            }
        }
    }

    override fun bindData() {
    }

    override fun finish() {
        super.finish()
        activityLifecycleCallbacks?.let {
            application.unregisterActivityLifecycleCallbacks(it)
        }
        overridePendingTransition(0, 0)
    }

    @RequiresApi(9999)
    @Deprecated("你不应该调用该方法", ReplaceWith("none"))
    override fun setContentView(view: View?) {
        super.setContentView(view)
    }

    override fun getDefFullBackgroundRes() = 0
}